<!--
 * @Author: Dorange.Wang
 * @Date: 2021-03-31 16:04:51
 * @LastEditors: wangming
 * @LastEditTime: 2022-04-07 17:52:14
 * @Description: file content
-->
<template>
  <el-dialog :visible="showVisible" center :show-close="false" width="600px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ title }}</span>
        <span
          class="el-icon-close g9 f26 poi"
          @click="showVisible = false"
        ></span>
      </div>
    </div>
    <el-form
      class="pl30 pr30"
      :model="formData"
      ref="form"
      label-width="120px"
      label-position="top"
    >
      <el-form-item
        label="模态框名称"
        prop="name"
        :rules="[
          { required: true, message: '请输入模态框名称', trigger: 'blur' },
        ]"
      >
        <el-input
          v-model="formData.name"
          style="width: 100%"
          placeholder="请输入模态框名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="模态框配置">
        <el-input
          :autosize="{ minRows: 10, maxRows: 20 }"
          v-model="config"
          style="width: 100%"
          type="textarea"
          placeholder="请粘贴模态框配置信息"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="showVisible = false">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  watch: {
    showVisible(v) {
      if (!v) {
        document.removeEventListener("paste", this.transitionEventText);
      }
    },
  },
  data() {
    return {
      config: "",
      title: "复制模态框",
      showVisible: false,
      formData: {
        name: "",
      },
      callback: () => {},
    };
  },
  methods: {
    async transitionEventText(event) {
      let paste = (event.clipboardData || window.clipboardData).getData("text");
      setTimeout(() => {
        try {
          this.config = paste;
          this.formData.name = JSON.parse(paste)?.name;
        } catch (error) {}
      }, 200);
    },
    addForm() {
      document.addEventListener("paste", this.transitionEventText);
      this.formData.name = "";
      this.config = "";
      return this.showModel();
    },
    showModel() {
      this.showVisible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
      return {
        then: (callback) => {
          if (typeof callback === "function") {
            this.callback = callback;
          }
        },
      };
    },
    async submit() {
      await this.$refs.form.validate();
      try {
        let formData = JSON.parse(this.config);
        this.showVisible = false;
        formData.name = this.formData.name;
        this.callback(formData);
      } catch (error) {
        this.$message.error("配置信息格式不正确");
        console.error(error);
      }
    },
  },
};
</script>

<style lang="scss" scoped></style>
